package com.lql.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.common.utils.CollUtils;
import com.lql.gateway.config.AuthProperties;
import com.lql.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request
        ServerHttpRequest request = exchange.getRequest();
        // 判断是否需要拦截
        if (isExclude(request.getPath().toString())) {
            // 不需要拦截，直接放行
            return chain.filter(exchange);
        }
        // 获取请求头中的token
        String token = null;
        List<String> authorization = request.getHeaders().get("authorization");
        if (CollUtils.isNotEmpty(authorization)) {
            token = authorization.get(0);
        }

        // 校验并解析token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            // token 无效，直接返回401
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        // 传递用户信息 将用户信息放入请求头中传递
        String userInfo = userId.toString();
        ServerWebExchange swx = exchange.mutate()
                .request(b -> b.header("userInfo", userInfo))
                .build();

        // 放行
        return chain.filter(swx);
    }

    private boolean isExclude(String path) {
        for(String excludePath : authProperties.getExcludePaths()){
            if(antPathMatcher.match(excludePath, path)){
                // 成功匹配到排除的路径，直接返回true
                return true;
            }
        }
        return false;
    }


    // 过滤器优先级，越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
